package ar.uba.fi.taller2.TreesWeb.ui.initiator;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import ar.uba.fi.taller2.TreesWeb.*;
import ar.uba.fi.taller2.TreesWeb.ui.*;
import org.zkoss.zk.ui.Page;
import org.zkoss.zk.ui.util.Initiator;

public class LookupInit implements Initiator
{
	
	
	private static HashMap lookups = null;
	
	public void doInit(Page arg0, Object[] arg1) throws Exception
	{
		arg0.setVariable((String) arg1[0], getLookup( (String) arg1[1] ) );
	}

	public boolean doCatch(Throwable arg0)
	{
		// TODO Auto-generated method stub
		return true;
	}

	public void doFinally()
	{
		// TODO Auto-generated method stub

	}

	
	private static List getLookup( String lookupName ) throws JDOMException, IOException
	{
		if (lookups == null)
		{
			lookups = new HashMap();
			File file = new File( Properties.getDataDir(), Properties.getLookupFile() );
			SAXBuilder parser = new SAXBuilder();		
			Document doc = parser.build( file );
			Element element = doc.getRootElement();
			List list =  element.getChildren("lookup");
			Iterator i = list.iterator();
			while ( i.hasNext() )
			{
				Element lookupElement = (Element) i.next();
				String id = lookupElement.getAttributeValue("id");
				List options = new ArrayList();
				
				Iterator lookupOptions = lookupElement.getChildren().iterator();
				
				while( lookupOptions.hasNext() )
				{
					Element option = (Element) lookupOptions.next();
					String optionId = option.getAttributeValue("id");
					String value = option.getChild("description").getText();
					Lookup lookup = new Lookup(id, optionId, value);
					options.add( lookup );
				}
				lookups.put(id, options);
			}
		}
		return (List) lookups.get( lookupName );
	}

	public void doAfterCompose(Page arg0) throws Exception {
		// TODO Auto-generated method stub
		
	}
}

